package com.hyzx.qbasic.admin.common.security;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 黄江华 on 2017/11/2
 */

@Component
public class ShiroFilerChainManager {
    private static final Logger logger = LoggerFactory.getLogger(ShiroFilerChainManager.class);

    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;
    private DefaultFilterChainManager filterChainManager;
    private Map<String, NamedFilterList> defaultFilterChains;

    @PostConstruct
    public void init() {
        AbstractShiroFilter shiroFilter = null;
        try {
            shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
        } catch (Exception ex) {
            logger.error("从ShiroFilterFactoryBean获取ShiroFilter异常");
            throw new RuntimeException("从ShiroFilterFactoryBean获取ShiroFilter异常");
        }

        PathMatchingFilterChainResolver filterChainResolver =
                (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
        filterChainManager = (DefaultFilterChainManager) filterChainResolver
                .getFilterChainManager();

        defaultFilterChains = new LinkedHashMap<>(filterChainManager.getFilterChains());
    }

    public synchronized void initFilterChains(List<UrlFilter> urlFilters) {
        //1、首先删除以前老的filter chain并注册默认的
        filterChainManager.getFilterChains().clear();
        if (defaultFilterChains != null) {
            filterChainManager.getFilterChains().putAll(defaultFilterChains);
        }

        //2、循环URL Filter 注册filter chain
        for (UrlFilter urlFilter : urlFilters) {
            //注册perms filter
            if (!StringUtils.isEmpty(urlFilter.getPermission())&&!StringUtils.isEmpty(urlFilter.getUrl())) {
                filterChainManager.addToChain(urlFilter.getUrl(), "perms",
                        urlFilter.getPermission());
            }
        }

        filterChainManager.addToChain("/**", "authc", "authc");
    }
}
